package com.wty.cmims.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wty.cmims.mapper.DoctorMapper;
import com.wty.cmims.mapper.HealthRecordMapper;
import com.wty.cmims.mapper.MedicalHistoryMapper;
import com.wty.cmims.mapper.PermissionMapper;
import com.wty.cmims.mapper.ResidentMapper;
import com.wty.cmims.pojo.Code;
import com.wty.cmims.pojo.Doctor;
import com.wty.cmims.pojo.MedicalHistory;
import com.wty.cmims.pojo.Permission;
import com.wty.cmims.pojo.Resident;
import com.wty.cmims.pojo.ResponseResult;
import com.wty.cmims.pojo.User;
import com.wty.cmims.service.PermissionService;
import com.wty.cmims.service.UserService;
import com.wty.cmims.mapper.UserMapper;
import com.wty.cmims.pojo.HealthRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author wty
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-11-04 21:23:30
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ResidentMapper residentMapper;
    @Autowired
    private HealthRecordMapper healthRecordMapper;
    @Autowired
    private MedicalHistoryMapper medicalHistoryMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private PermissionService permissionService;

    @Override
    public ResponseResult<Map<String, Object>> userLogin(String account, String password, Integer role) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        // 对密码进行MD5加密并加盐
        password = SecureUtil.md5(password + account);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount,account);
        wrapper.eq(User::getPassword,password);
        wrapper.eq(User::getRole,role);
        wrapper.eq(User::getIsDel,0);
        User user = this.getOne(wrapper);
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("account",account);
        paramsMap.put("role",role);
        Map<String, Object> map;
        Map<String, Object> mapPermission;
        List<Map<String, Object>> list = new ArrayList<>();
        if (role == 1){
            map = doctorMapper.findDoctorInfo(paramsMap);
            mapPermission = permissionMapper.findPermission(paramsMap);
            if (map != null && mapPermission != null){
                list.add(map);
                list.add(mapPermission);
            }
        } else {
            map = userMapper.findAdminInfo(paramsMap);
            mapPermission = permissionMapper.findPermission(paramsMap);
            if (map != null && mapPermission != null){
                list.add(map);
                list.add(mapPermission);
            }
        }
        if (user != null){
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("登录成功");
            responseResult.setDatas(list);
        }else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("账号或密码错误");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Map<String,Object>> adminInfoUpdate(Map<String,Object> paramsMap) {
        ResponseResult<Map<String,Object>> responseResult = new ResponseResult<>();
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getAccount,paramsMap.get("account"));
        wrapper.set(User::getName,paramsMap.get("name"));
        wrapper.set(User::getEmail,paramsMap.get("email"));
        wrapper.set(User::getPhone,paramsMap.get("phone"));
        wrapper.set(User::getUserImg,paramsMap.get("user_img"));
        boolean update = this.update(wrapper);
        Map<String, Object> adminInfo = userMapper.findAdminInfo(paramsMap);
        if (update && adminInfo != null) {
            responseResult.setData(adminInfo);
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("修改成功");
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("修改失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Void> resetPassword(Integer userId) {
        ResponseResult<Void> responseResult = new ResponseResult<>();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserId,userId);
        User user = this.getOne(wrapper);
        user.setPassword(SecureUtil.md5("000000" + user.getAccount()));
        boolean update = this.update(user,wrapper);
        if (update) {
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("密码重置成功");
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("密码重置失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Void> deleteUser(Integer userId) {
        ResponseResult<Void> responseResult = new ResponseResult<>();
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUserId,userId);
        wrapper.set(User::getIsDel,1);
        boolean update = this.update(wrapper);
        if (update) {
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("账号删除成功");
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("账号删除失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Void> updatePassword(String account, String oldPassword, String newPassword) {
        ResponseResult<Void> responseResult = new ResponseResult<>();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, account).eq(User::getPassword, SecureUtil.md5(oldPassword + account));
        User user = this.getOne(wrapper);
        if (user == null){
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("旧密码输入错误");
            return responseResult;
        }
        user.setPassword(SecureUtil.md5(newPassword + account));
        boolean update = this.updateById(user);
        if(update){
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("密码修改成功");
        } else{
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("密码修改失败");
        }
        return responseResult;
    }

    @Transactional
    @Override
    public ResponseResult<Void> userRegister(String name, String account, String phone, Integer title_id, Integer department_id, Integer institution_id, Integer fee, Integer role) {
        ResponseResult<Void> responseResult = new ResponseResult<>();
        // 判断账号是否已存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, account).eq(User::getIsDel, 0);
        User same = this.getOne(wrapper);
        if (same != null){
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("账号" + account + "已注册");
            return responseResult;
        }
        // 判断手机号是否已注册
        LambdaQueryWrapper<User> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(User::getPhone, phone).eq(User::getIsDel, 0);
        User same2 = this.getOne(wrapper2);
        if (same2 != null){
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("手机号" + phone + "已注册");
            return responseResult;
        }
        // 创建User对象赋值并插入数据表
        User user = new User();
        user.setName(name);
        user.setAccount(account);
        user.setPhone(phone);
        // 密码进行MD5加密并加盐（初始密码000000）
        user.setPassword(SecureUtil.md5("000000" + account));
        user.setRole(role);
        user.setIsDel(0);
        boolean save = this.save(user);
        if (save){
            if (role == 0){
                Resident resident = new Resident();
                resident.setUserId(user.getUserId());
                // 在resident表中插入一条只有user_id的数据
                int rowsResident = residentMapper.insert(resident);
                // 在healthrecord表中插入一条只有id和resident_id的数据
                HealthRecord healthRecord = new HealthRecord();
                healthRecord.setResidentId(resident.getUserId());
                int rowsHealthrecord = healthRecordMapper.insert(healthRecord);
                // 居民相关信息全部注册成功，获取居民基本信息
                if (rowsResident > 0 && rowsHealthrecord > 0) {
                    responseResult.setCode(Code.SUCCESS);
                    responseResult.setMessage("居民账号添加成功");
                } else {
                    responseResult.setCode(Code.ERROR);
                    responseResult.setMessage("居民相关信息添加失败");
                }
            } else if(role == 1){
                Doctor doctor = new Doctor();
                doctor.setUserId(user.getUserId());
                doctor.setTitleId(title_id);
                doctor.setDepartmentId(department_id);
                doctor.setInstitutionId(institution_id);
                doctor.setFee(fee);
                // 在doctor表中插入数据
                int rowsDoctor = doctorMapper.insert(doctor);
                // 在permission表中插入一条该医生的数据
                Permission permission = new Permission();
                permission.setUserId(doctor.getUserId());
                permission.setAppointmentDoctor(1);
                permission.setEvaluation(0);
                int rowsDoctorPermission = permissionMapper.insert(permission);
                // 医生相关信息全部注册成功，获取居民基本信息
                if (rowsDoctor > 0 && rowsDoctorPermission > 0) {
                    responseResult.setCode(Code.SUCCESS);
                    responseResult.setMessage("医生账号添加成功");
                } else {
                    responseResult.setCode(Code.ERROR);
                    responseResult.setMessage("医生信息添加失败");
                }
            } else {
                // 在permission表中插入一条该管理员的数据
                Permission permission = new Permission();
                permission.setUserId(user.getUserId());
                permission.setResident(1);
                permission.setDoctor(1);
                permission.setAdmin(0);
                permission.setInstitution(1);
                permission.setMedicationDevice(0);
                permission.setTypeInfo(0);
                permission.setAppointmentAdmin(0);
                permission.setAppointmentDoctor(0);
                permission.setRoleManage(0);
                permission.setAnnouncement(0);
                permission.setOpinion(0);
                int rowsAdminPermission = permissionMapper.insert(permission);
                if (rowsAdminPermission > 0) {
                    responseResult.setCode(Code.SUCCESS);
                    responseResult.setMessage("管理员账号添加成功");
                } else {
                    responseResult.setCode(Code.ERROR);
                    responseResult.setMessage("管理员账号添加失败");
                }
            }
        } else{
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("添加失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Map<String, Object>> findAdmin(Map<String, Object> paramsMap) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        Integer pageSize = (Integer) paramsMap.get("pageSize");
        paramsMap.put("start", ((Integer) paramsMap.get("currentPage") - 1) * pageSize);
        responseResult.setPageSize(pageSize);
        List<Map<String, Object>> admins = userMapper.findAdmin(paramsMap);
        Integer total = userMapper.findAdminNum(paramsMap);
        if (admins != null) {
            responseResult.setDatas(admins);
            responseResult.setTotal(total);
            responseResult.setCurrentPage((Integer) paramsMap.get("currentPage"));
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("管理员账号查询成功");
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("管理员账号查询失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Map<String, Object>> updateAdmin(Map<String, Object> paramsMap) {
        ResponseResult<Map<String,Object>> responseResult = new ResponseResult<>();
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUserId,paramsMap.get("user_id"));
        wrapper.set(User::getAccount,paramsMap.get("account"));
        wrapper.set(User::getName,paramsMap.get("name"));
        wrapper.set(User::getEmail,paramsMap.get("email"));
        wrapper.set(User::getPhone,paramsMap.get("phone"));
        wrapper.set(User::getUserImg,paramsMap.get("user_img"));
        boolean update = this.update(wrapper);
        Map<String, Object> adminInfo = userMapper.findAdminInfo(paramsMap);
        if (update && adminInfo != null) {
            responseResult.setData(adminInfo);
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("管理员信息更新成功");
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("管理员信息更新失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Map<String, Object>> findDoctorAndAdmin(Map<String, Object> paramsMap) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        Integer pageSize = (Integer) paramsMap.get("pageSize");
        paramsMap.put("start", ((Integer) paramsMap.get("currentPage") - 1) * pageSize);
        responseResult.setPageSize(pageSize);

        List<Map<String, Object>> roles = userMapper.findDoctorAndAdmin(paramsMap);
        Integer total = userMapper.findDoctorAndAdminNum(paramsMap);
        if (roles != null) {
            responseResult.setDatas(roles);
            responseResult.setTotal(total);
            responseResult.setCurrentPage((Integer) paramsMap.get("currentPage"));
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("角色账号查询成功");
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("角色账号查询失败");
        }
        return responseResult;
    }

    @Override
    @Transactional
    public ResponseResult<Void> updateRole(Map<String,Object> paramsMap) {
        ResponseResult<Void> responseResult = new ResponseResult<>();
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUserId,paramsMap.get("user_id"));
        wrapper.set(User::getRole,paramsMap.get("role"));
        boolean updateRole = this.update(wrapper);
        // 修改为对应的角色权限
        int role = Integer.parseInt(paramsMap.get("role").toString());
        LambdaUpdateWrapper<Permission> wrapperUpdate = new LambdaUpdateWrapper<>();
        if (role == 1){
            // 查询doctor表里是否有该账号信息
            LambdaQueryWrapper<Doctor> wrapperDoctor = new LambdaQueryWrapper<>();
            wrapperDoctor.eq(Doctor::getUserId,paramsMap.get("user_id"));
            Doctor doctor = doctorMapper.selectOne(wrapperDoctor);
            if (doctor == null){
                doctor = new Doctor();
                doctor.setUserId((Integer) paramsMap.get("user_id"));
//                doctor.setTitleId(0);
//                doctor.setDepartmentId(0);
//                doctor.setInstitutionId(0);
//                doctor.setFee(0);
                // 在doctor表中插入数据
                int rowsDoctor = doctorMapper.insert(doctor);
            }
            wrapperUpdate.eq(Permission::getUserId,paramsMap.get("user_id"));
            wrapperUpdate.set(Permission::getResident,0);
            wrapperUpdate.set(Permission::getDoctor,0);
            wrapperUpdate.set(Permission::getAdmin,0);
            wrapperUpdate.set(Permission::getInstitution,0);
            wrapperUpdate.set(Permission::getMedicationDevice,0);
            wrapperUpdate.set(Permission::getTypeInfo,0);
            wrapperUpdate.set(Permission::getAppointmentAdmin,0);
            wrapperUpdate.set(Permission::getAppointmentDoctor,1);
            wrapperUpdate.set(Permission::getRoleManage,0);
        } else {
            wrapperUpdate.eq(Permission::getUserId,paramsMap.get("user_id"));
            wrapperUpdate.set(Permission::getResident,1);
            wrapperUpdate.set(Permission::getDoctor,1);
            wrapperUpdate.set(Permission::getAdmin,0);
            wrapperUpdate.set(Permission::getInstitution,1);
            wrapperUpdate.set(Permission::getMedicationDevice,0);
            wrapperUpdate.set(Permission::getTypeInfo,0);
            wrapperUpdate.set(Permission::getAppointmentAdmin,0);
            wrapperUpdate.set(Permission::getAppointmentDoctor,0);
            wrapperUpdate.set(Permission::getRoleManage,0);
        }
        boolean updatePermission = permissionService.update(wrapperUpdate);
        if (updateRole && updatePermission) {
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("角色更新成功");
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("角色更新失败");
        }
        return responseResult;
    }
}